package filesystems

import (
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/toolbox"
	"github.com/rcrowley/go-metrics"
	"github.com/shirou/gopsutil/disk"
)

var (
	StatusError error
	Register    metrics.Registry
)

func init() {
	Register = metrics.NewRegistry()
	tk := toolbox.NewTask("GetFileSystemTask", "*/1 * * * * *", GetFileSystemTask)
	toolbox.AddTask("GetFileSystemTask", tk)
}

// TODO 对文件系统进行深度获取监控
func GetFileSystemTask() error {
	var Partitions []disk.PartitionStat
	Partitions, StatusError = disk.Partitions(true)
	if StatusError != nil {
		Register.UnregisterAll()
		return StatusError
	}
	Register.UnregisterAll()
	for _, p := range Partitions {
		if p.Fstype == "ext4" || p.Fstype == "xfs" || p.Fstype == "NTFS" {
			status, err := disk.Usage(p.Mountpoint)
			if err != nil {
				logs.Error(err)
			} else {
				//a, _ := disk.IOCounters(p.Device)
				//logs.Info(a)
				m := metrics.GetOrRegisterGaugeFloat64(p.Mountpoint, Register)
				m.Update(status.UsedPercent)
			}
		}
	}

	return nil
}

func RootSize() uint64 {
	status, err := disk.Usage("/")
	if err != nil {
		logs.Error(err.Error())
		return 0
	}
	return status.Total
}

func DataSize() uint64 {
	status, err := disk.Usage("/data")
	if err != nil {
		logs.Error(err.Error())
		return 0
	}
	return status.Total
}
